package com.example.dou2204.live;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.BounceInterpolator;
import android.widget.ImageView;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.example.dou2204.R;
import com.example.dou2204.adapter.GiftAdapter;
import com.example.dou2204.adapter.MessageAdapter;
import com.example.dou2204.baseMVVM.BaseActivity;
import com.example.dou2204.databinding.ActivityLiveBinding;
import com.example.dou2204.entity.GiftEntity;
import com.example.dou2204.entity.MessageEntity;
import com.example.dou2204.entity.MoneyEntity;
import com.example.dou2204.entity.ResultEntity;
import com.example.dou2204.entity.VideoEntity;
import com.example.dou2204.pay.PayActivity;
import com.example.dou2204.roomdb.DataBaseUtils;

import java.util.ArrayList;
import java.util.List;

import master.flame.danmaku.danmaku.model.BaseDanmaku;
import master.flame.danmaku.danmaku.model.IDanmakus;
import master.flame.danmaku.danmaku.model.android.DanmakuContext;
import master.flame.danmaku.danmaku.model.android.Danmakus;
import master.flame.danmaku.danmaku.parser.BaseDanmakuParser;
import top.littlefogcat.danmakulib.danmaku.Danmaku;
import top.littlefogcat.danmakulib.danmaku.DanmakuManager;

public class LiveActivity extends BaseActivity<ActivityLiveBinding,LiveViewModel> {
    VideoEntity.DataBean video;

    List<GiftEntity.DataBean> gifts = new ArrayList<>();
    GiftAdapter giftAdapter;
    MoneyEntity money;
    int giftIndex = -1;//下标为-1，代表未选礼物
    ImageView imageView;//展示礼物图片的
    private GiftControl giftControl;
    private DanmakuContext danmakuContext;//弹幕上下文
    //弹幕解析器
    private BaseDanmakuParser danmakuParser = new BaseDanmakuParser() {
        @Override
        protected IDanmakus parse() {
            return new Danmakus();
        }
    };

    List<MessageEntity> messages = new ArrayList<>();
    MessageAdapter messageAdapter;

    @Override
    protected void initData() {
        viewModel.guanSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    video.setGuanzhu(1);
                    binding.tvGuanzhu.setText("粉丝");
                }
            }
        });
        viewModel.noguanSuccess.observe(this, new Observer<ResultEntity>() {
            @Override
            public void onChanged(ResultEntity entity) {
                if(entity.getCode()==200){
                    ToastUtils.showLong(entity.getMessage());
                    video.setGuanzhu(0);
                    binding.tvGuanzhu.setText("关注");
                }
            }
        });

        viewModel.giftSuccess.observe(this, new Observer<GiftEntity>() {
            @Override
            public void onChanged(GiftEntity entity) {
                if(entity.getCode()==200){
                    gifts.clear();
                    gifts.addAll(entity.getData());
                    giftAdapter.notifyDataSetChanged();
                }
            }
        });
    }

    @Override
    protected void initView() {
        video = (VideoEntity.DataBean) getIntent().getExtras().get("video");
        initUserGsy();//初始化左上角用户信息，以及视频播放器的信息
        initGift();//初始化礼物列表
        initMoney();//初始化余额信息
        initDanmuView();//初始化弹幕信息
        initMessage();//初始化左下角信息
        giftControl = new GiftControl(binding.giftLayout);

        binding.videoClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();//结束当前activity
            }
        });
        binding.tvGuanzhu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(video.getGuanzhu()==1){
                   //执行取消关注
                    viewModel.noguanzhu(video.getAuthname());
                }else {
                    //执行关注
                    viewModel.guanzhu(video.getAuthname());
                }
            }
        });
        binding.ivDianzan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //实现贝塞尔曲线的动画效果
                binding.ksgView.addLikeImages(R.drawable.ic_xihuanred,R.drawable.ic_shoucangyellow,R.drawable.ic_gift);
                binding.ksgView.addFavor();
            }
        });
        //点击礼物图标，展示礼物列表
        binding.ivGift.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clGift.setVisibility(View.VISIBLE);
                //加载礼物数据
                viewModel.gift();
            }
        });
        binding.giftClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clGift.setVisibility(View.GONE);
            }
        });
        binding.tvGoMoney.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //startActivity(new Intent(LiveActivity.this, PayActivity.class));
                startActivityForResult(new Intent(LiveActivity.this, PayActivity.class),200);
            }
        });
        binding.tvMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                binding.clEt.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(LiveActivity.this, R.anim.in);
                animation.setInterpolator(new BounceInterpolator());
                binding.clEt.startAnimation(animation);
                binding.etMessage.requestFocus();//获取焦点，方便后续去输入文字
            }
        });
        //实现发送弹幕
        binding.etSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String string = binding.etMessage.getText().toString();
                //简单弹幕实现
                /*DanmakuManager.getInstance().init(LiveActivity.this,binding.easeDanmu);
                Danmaku danmaku = new Danmaku();
                danmaku.text = string;
                danmaku.color = "#FF03DAC5";
                danmaku.size = 60;
                danmaku.mode = Danmaku.Mode.scroll;//滚动
                DanmakuManager.getInstance().send(danmaku);*/
                //烈焰弹幕实现
                binding.danmuview.enableDanmakuDrawingCache(false);//是否开始弹幕绘制缓存
                binding.danmuview.removeAllDanmakus(true);//不然会把之前的弹幕显示出来
                binding.danmuview.clear();
                //创建弹幕实体类
                BaseDanmaku danmaku = danmakuContext.mDanmakuFactory.createDanmaku(BaseDanmaku.TYPE_SCROLL_RL);
                danmaku.text = string;
                danmaku.textColor = Color.RED;
                danmaku.borderColor = Color.GREEN;
                danmaku.textShadowColor = Color.BLUE;
                danmaku.underlineColor = Color.YELLOW;
                danmaku.textSize = 60;
                danmaku.setTime(800);
                binding.danmuview.addDanmaku(danmaku);
                binding.danmuview.start();//开始绘制
                binding.etMessage.setText("");
                binding.clEt.setVisibility(View.GONE);
                //在左下角添加消息
                MessageEntity entity = new MessageEntity(string,SPUtils.getInstance().getString("username"));
                messages.add(entity);
                binding.messageRv.scrollToPosition(messages.size()-1);
                messageAdapter.notifyDataSetChanged();
            }
        });

        //点击选中的礼物
        giftAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
                //拿到下标，方便后续去执行发送礼物的操作
                Glide.with(LiveActivity.this).load(gifts.get(position).getGiftpath()).into(binding.giftChecked);
                giftIndex = position;
            }
        });
        //点击发送按钮，实现发送礼物
        binding.giftSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(giftIndex<0){
                    ToastUtils.showLong("您未选中任何礼物，请进行选择");
                    return;
                }
                if(money.getSum()<gifts.get(giftIndex).getPrice()){
                    ToastUtils.showLong("您的余额不足，请选择其他礼物或者进行充值");
                    return;
                }
                //更新余额
                money.setSum(money.getSum()-gifts.get(giftIndex).getPrice());
                DataBaseUtils.getInstance().getMoneyDao().updateMoney(money);//更新数据库中数据
                // ---在实际应用中，需判断更新后台是否成功，成功后再修改页面值，发送礼物特效，防止后台数据和页面数据不一致的问题
                binding.tvMoney.setText(money.getSum()+"缘");//更新页面
                giftControl.loadGIft(gifts.get(giftIndex));
                sendGift();
            }
        });
    }

    private void initMessage() {
        messageAdapter = new MessageAdapter(R.layout.item_message,messages);
        binding.messageRv.setAdapter(messageAdapter);
        binding.messageRv.setLayoutManager(new LinearLayoutManager(this));
        binding.messageRv.scrollToPosition(messages.size()-1);//自动滚到到最新的一条
    }

    private void initDanmuView() {
        //实例化上下文
        danmakuContext = DanmakuContext.create();
        binding.danmuview.enableDanmakuDrawingCache(false);//是否开始弹幕绘制缓存
        binding.danmuview.clear();
        binding.danmuview.removeAllDanmakus(true);
        binding.danmuview.prepare(danmakuParser,danmakuContext);
    }

    private void sendGift() {
        if(imageView==null){
            imageView = new ImageView(this);
            ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(200, 200);
            imageView.setLayoutParams(params);
            Glide.with(this).load(gifts.get(giftIndex).getGiftpath()).into(imageView);
            binding.clLive.addView(imageView);//可以显示在直播间了
        }else {
            imageView.setVisibility(View.VISIBLE);
            Glide.with(this).load(gifts.get(giftIndex).getGiftpath()).into(imageView);
        }
        //添加动画效果进行展示
        //从屏幕左上角飞出，最终停留在屏幕中间
        int width = getWindowManager().getDefaultDisplay().getWidth();
        int height = getWindowManager().getDefaultDisplay().getHeight();
        ObjectAnimator translationX = ObjectAnimator.ofFloat(imageView, "translationX", 0, width, width * 2 / 5, width / 2 - 100).setDuration(2000);
        ObjectAnimator translationY = ObjectAnimator.ofFloat(imageView, "translationY", height, height*4/5,height*3/5,height/2-100).setDuration(2000);

        ObjectAnimator rotation = ObjectAnimator.ofFloat(imageView, "rotation", 0, 360).setDuration(1000);
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(imageView, "scaleX", 1, 2, 1).setDuration(1000);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(imageView, "scaleY", 1, 2, 1).setDuration(1000);
        ObjectAnimator alpha = ObjectAnimator.ofFloat(imageView, "alpha", 1, 0, 1).setDuration(1000);

        AnimatorSet set = new AnimatorSet();
        set.play(translationX).with(translationY).before(rotation).before(scaleX).before(scaleY).before(alpha);
        set.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                imageView.setVisibility(View.GONE);//动画结束后，图片隐藏
            }
        });
        set.start();
    }

    private void initMoney() {
        //当前账号是否存在---存在，展示余额信息 ====不存在创建一个新账号
        money = DataBaseUtils.getInstance().getMoneyDao().queryMoney(SPUtils.getInstance().getString("username"));
        if(money == null){
            money = new MoneyEntity(SPUtils.getInstance().getString("username"),0);
            DataBaseUtils.getInstance().getMoneyDao().insertMoney(money);
        }
        binding.tvMoney.setText(money.getSum()+"缘");
    }

    private void initGift() {
        binding.rvGift.setLayoutManager(new GridLayoutManager(this,4));
        giftAdapter = new GiftAdapter(R.layout.item_gift,gifts);
        binding.rvGift.setAdapter(giftAdapter);
    }

    private void initUserGsy() {
        Glide.with(this).load(video.getHeadpath()).into(binding.ivUser);//用户头像
        binding.tvUser.setText(video.getAuthname());//用户名称
        if(video.getGuanzhu()==1){
            binding.tvGuanzhu.setText("粉丝");
        }else {
            binding.tvGuanzhu.setText("关注");
        }
        //视频播放器的内容
        binding.gsy.setUp(video.getVideopath(),true,"");
        binding.gsy.getBackButton().setVisibility(View.GONE);
        binding.gsy.getStartButton().setVisibility(View.GONE);
        binding.gsy.startPlayLogic();
    }

    @Override
    protected int bindLayout() {
        return R.layout.activity_live;
    }

    @Override
    protected Class<LiveViewModel> getViewModel() {
        return LiveViewModel.class;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==200&&resultCode==201){
            initMoney();
        }
    }
}